﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


using LearnNet.BLL;
using System.Xml;
using LearnNet.Common;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Collections;
using mshtml;
using LearnNet.Forum;

namespace BBSReport
{
    public partial class frmLogin : Form
    {
        public frmLogin()
        {
            InitializeComponent();
        }
        private XmlHelper xmlHelper = new XmlHelper(string.Concat(Application.StartupPath, "/config.xml"));
        public System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private int state = 0;
        private void frmLogin_Load(object sender, EventArgs e)
        {
            this.webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
            this.webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
            this.webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
            this.webBrowser1.NewWindow += new CancelEventHandler(webBrowser1_NewWindow);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = 2000;
            timer.Enabled = false;
        }

        private void btnG_Click(object sender, EventArgs e)
        {
            if (tbPwd.Text == "" || tbUrl.Text == "" || tbUser.Text == "")
            {
                MessageBox.Show("请先填写内容");
            }
            timer.Enabled = true;
            
        }

        public void timer_Tick(object sender, EventArgs e)
        {

            // this.webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);

            string str = string.Empty;
            //UpdateInfo upInfo = new UpdateInfo();
            //upInfo.Count = dt.Rows.Count;
            //upInfo.Index = 0;
            string strSql = string.Empty;
           
            string strMessage = string.Empty;
            if (state == 0)
            {



                this.webBrowser1.Navigate("about:blank");
             


            }
            try
            {
               
                switch (state)
                {
                    case 0:
                        {

                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@url='" +tbUrl.Text  + "']/logout", "url"));
                            state = 1;
                            timer.Enabled = false;
                            break;
                        }

                    case 1:
                        {
                            webBrowser1.Url = new Uri(xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/login", "url"));
                            state = 2;
                            timer.Enabled = false;
                            break;
                        }
                    case 2:
                        {
                            string strReturn = string.Empty;
                            if (!ReportHelper.SetAttribute("root/station[@url='" + tbUrl.Text + "']/login/name", tbUser.Text, webBrowser1, xmlHelper))
                            {
                                strReturn += "名称设置出错!";
                            }
                            if (!ReportHelper.SetAttribute("root/station[@url='" + tbUrl.Text + "']/login/pwd", tbPwd.Text, webBrowser1, xmlHelper))
                            {
                                strReturn += "密码设置出错!";
                            }
                            if (!ReportHelper.SetAttribute("root/station[@url='" + tbUrl.Text + "']/login/checkbox", "true", webBrowser1, xmlHelper))
                            {
                                strReturn += "保存密码设置出错!";
                            }

                            try
                            {
                                object obj = null;
                                if (string.IsNullOrEmpty(xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/login/button", "key")))
                                {
                                    if (!string.IsNullOrEmpty(xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/login/form", "index")))
                                    {
                                        obj = webBrowser1.Document.Forms[Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/login/form", "index"), 0)].InvokeMember("submit");
                                    }
                                    else
                                    {
                                        strReturn += "xml配置错误";
                                    }
                                }
                                else
                                {
                                    obj = webBrowser1.Document.GetElementById(xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/login/button", "key")).InvokeMember("click");
                                }




                            }
                            catch (Exception ex)
                            {

                                strReturn += ex.Message;
                               
                            }
                            finally
                            {
                                state = 3;
                                timer.Enabled = false;
                            }
                            strMessage = strReturn + strMessage;
                          
                            break;
                        }

                    default:
                        {
                            timer.Enabled = false;
                            break;
                        }

                }
                
            }
            catch (Exception ex)
            {
                state = 0;
                timer.Enabled = true;
                strMessage += ex.Message;
                MessageBox.Show(strMessage);
            }



        }



        protected void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.ToString() != webBrowser1.Url.ToString())
                return;
            if (webBrowser1.ReadyState.ToString() == WebBrowserReadyState.Complete.ToString())
            {

                this.webBrowser1.Document.Window.Error += new HtmlElementErrorEventHandler(Window_Error);

                if (state == 3)
                {
                    timer.Enabled = false;
                }
                else
                {
                    timer.Enabled = true;

                }

            }
        }
       
      

        #region 监听webBrowser事件
        void Document_Click(object sender, HtmlElementEventArgs e)
        {
            //MessageBox.Show(e.EventType);
            //MessageBox.Show(e.FromElement.Id + e.FromElement.InnerHtml);

        }

        void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            //e.Cancel = true;
        }

        protected void Window_Error(object sender, HtmlElementErrorEventArgs e)
        {
            e.Handled = true;
        }

        public bool iEvent_onclick(IHTMLEventObj pEvtObj)
        {
            //MessageBox.Show(pEvtObj.qualifier);
            return true;
        }
        // 事件处理函数,目的，不使用WebBrowser自己的菜单。 
        private bool ContextMenuEventHandler(IHTMLEventObj e)
        {
            MessageBox.Show("ContextMenuEventHanderl");
            return false;
        }


        protected void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            HtmlDocument hd = webBrowser1.Document;
            IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
            string s = @"function confirm() {";
            s += @"return true;";
            s += @"}";
            s = @"function killerrors() { return true; } window.onerror = killerrors; ";

            s += @"function alert() {}";
            s += @"window.onbeforeunload = function(){};$('vForm').onsubmit=function(){} ";
            win.execScript(s, "javascript");


            //禁用js弹出窗
            //HtmlDocument hd = webBrowser1.Document;
            //    IHTMLWindow2 win = (IHTMLWindow2)hd.Window.DomWindow;
            //    string s = @"function confirm() {";
            //    s += @"return true;";
            //    s += @"}";
            //    s = @"function killerrors() { return true; } window.onerror = killerrors; ";
            //    s += @"function alert() {}";
            //    s += @"window.onbeforeunload = function(){}; ";
            //    win.execScript(s, "javascript");

        }
        protected void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            //MessageBox.Show(webBrowser1.ReadyState.ToString());
        }
        #endregion

        private void btnCollect_Click(object sender, EventArgs e)
        {
            string siteUrl = "http://";
            siteUrl = string.Concat(siteUrl, tbUrl.Text);
            int collectListNum = 0;//采集列表数量
            string collectListUrl = xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/urlList", "url");
            string collectInWord = xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/urlCollect", "InWord");
            collectListNum = Utils.StringToInt(xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']/urlList", "count"), 0);
            string strEncoding = xmlHelper.GetAttribute("root/station[@url='" + tbUrl.Text + "']", "encoding");
          
            for (int i = 1; i <= collectListNum; i++)
            {
                CollectData clData = new CollectData();
                string strRequest = Utils.GetRequestString(string.Concat(siteUrl,"/", collectListUrl.Replace("$0", i.ToString())), 8000, 0, Encoding.GetEncoding(strEncoding));
                clData.GetLinkHref(strRequest, collectInWord, siteUrl);
                foreach (LearnNet.Entity.CollectPageInfo pageInfo in clData.getLinksInfo.Pages.Values)
                {
                    tbCollectUrl.Text = tbCollectUrl.Text + pageInfo.Url + "\r\n";
                }
            }
        }
    }
}
